package org.itworks.biodev.gui.panels;

import java.awt.event.ActionEvent;
import java.util.Vector;

import javax.swing.JOptionPane;

import org.itworks.biodev.gui.*;
import org.itworks.biodev.model.*;
import org.itworks.helpers.mvc.*;

public class SalesPanelControler extends AbstractControler {

	private SalesPanelModel model;
	
	public SalesPanelControler(SalesPanelModel model) {
		this.model = model;
	}
	
	public SalesPanelModel getModel() {
		return this.model;
	}
	/**
	 * 
	 * @param actionEvent
	 * @throws Exception
	 */
	public void createNewSaleButtonActionPerformed(ActionEvent actionEvent) throws Exception {
		// TODO Auto-generated method stub
		
		EditSaleDialogView editDialog = new EditSaleDialogView( new EditSaleDialogControler( new EditSaleDialogModel(), null));
		editDialog.setModal(true);
		editDialog.setVisible(true);
			
		try{
			this.model.setSalesList(SaleTable.getInstance().findAll());
		} catch(Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void viewLoaded() {
		// TODO Auto-generated method stub
		try {
			this.model.setSalesList(SaleTable.getInstance().findAll());
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
	}
	
	public void buttonColumnSalesActionPerformed(ActionEvent actionEvent,
			int selectedIndex) {
		// TODO Auto-generated method stub
		try {
			Sale saleToEdit = this.model.getSales().elementAt(selectedIndex);
			EditSaleDialogView editDialog = new EditSaleDialogView( new EditSaleDialogControler( new EditSaleDialogModel(),saleToEdit));
			editDialog.setModal(true);
			editDialog.setVisible(true);
			
			//if(editDialog.getIsOK()) {
				this.model.setSalesList(SaleTable.getInstance().findAll());
			//}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void deleteSelectedSalesButtonActionPerformed(
			ActionEvent actionEvent, Vector<Integer> selectedIndexes) {
		// TODO Auto-generated method stub
		if(selectedIndexes.size() > 0) {
			if(JOptionPane.showConfirmDialog(
					null,
					"Etes vous sur de vouloir supprimer les ventes selectionnnees ?",
					"Confirmation", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) {
				// Suppression
				for(Integer i : selectedIndexes) {
					Sale s;
					try {
						s = SaleTable.getInstance().find(i);
						
						SaleTable.getInstance().delete(s);
	
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				
				try {
					this.model.setSalesList(SaleTable.getInstance().findAll());
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
	}
}
